#include "RandomMech.h"
#include "Mech.h"
#include "HeroMech.h"
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"

USING_NS_CC;
using namespace CocosDenshion;

RandomMech::RandomMech() : Mech()
{
	_layer = NULL;
	_timeForNextShoot = 0;
}

bool RandomMech::initWithLayer(HelloWorld *layer,int kind,int hp)
{
	if( Mech::initWithLayer(layer,kind,hp) )
	{
		_layer = layer;
		this->schedule(schedule_selector(RandomMech::move),0.5);
		return true;
	}

    return false;
}


bool RandomMech::shouldShoot()
{
	if (ccpDistance(this->getPosition(), _layer->mech->getPosition()) > 600) return false;
 
    if (_timeSinceLastShot > _timeForNextShoot) {        
        _timeSinceLastShot = 0;
        _timeForNextShoot = (CCRANDOM_0_1() * 3) + 1;
        this->shootToward(_layer->mech->getPosition());
        return true;
    }
	return false;
}

void RandomMech::calcNextMove()
{
	bool moveOK = false;
	CCPoint start = _layer->tileCoordForPosition(this->getPosition());
    CCPoint end;
 
    while (!moveOK) 
	{
        end = start;
        end.x += CCRANDOM_MINUS1_1() * (abs(rand() % 10) + 3);
        end.y += CCRANDOM_MINUS1_1() * (abs(rand() % 10) + 3);
 
		moveOK = this->clearPathFromTileCoord(start,end);
    }    
 
	CCPoint moveToward = _layer->positionForTileCoord(end);
 
    this->moving = true;
	this->moveToward(moveToward);    
}

void RandomMech::move(float dt)
{
    if (this->moving && abs(rand() % 3) != 0) return;
	this->calcNextMove();
}

// From http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html
bool RandomMech::clearPathFromTileCoord(CCPoint start,CCPoint end)
{
    int dx = abs(end.x - start.x);
    int dy = abs(end.y - start.y);
    int x = start.x;
    int y = start.y;
    int n = 1 + dx + dy;
    int x_inc = (end.x > start.x) ? 1 : -1;
    int y_inc = (end.y > start.y) ? 1 : -1;
    int error = dx - dy;
    dx *= 2;
    dy *= 2;
 
    for (; n > 0; --n)
    {
        if ( _layer->isWallAtTileCoord(ccp(x, y)) ) return false;
 
        if (error > 0)
        {
            x += x_inc;
            error -= dy;
        }
        else
        {
            y += y_inc;
            error += dx;
        }
    }
 
    return true;
}

